package com.yanxu.threadlocal;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2025/3/9-2025
 * @Description: ThreadLocal 解决链路中参数层层传递的问题
 */
public class ThreadLocal05 {
    public static void main(String[] args) {
        Service1 service1 = new Service1();
        service1.process("超哥");
    }
}
class Service1 {
    public void process(String name) {
        User user = new User(name);
        UserContextHolder.holder.set(user);
        new Service2().process();
    }
}

//service2 在获取用户信息的时候，直接从ThreadLocal中获取。
class Service2 {
    public void process() {
        User user = UserContextHolder.holder.get();
        System.out.println("Service2拿到用户名：" + user.name);
        new Service3().process();
    }
}

//service3 在获取用户信息的时候，直接从ThreadLocal中获取。
class Service3 {
    public void process() {
        User user = UserContextHolder.holder.get();
        System.out.println("Service3拿到用户名：" + user.name);
        UserContextHolder.holder.remove();
    }
}


class User {
    String name;
    public User(String name) {
        this.name = name;
    }
}

class UserContextHolder {
    public static ThreadLocal<User> holder = new ThreadLocal<>();
}